package com.yh.csx.crm.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yh.csx.crm.core.exception.BusinessException;
import com.yh.csx.crm.core.util.HttpUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Huang Zhaoping
 * @date 2019/3/11
 */
@Service
public class GeoService {
    @Value("${map.securityKey}")
    private String securityKey;

    @Value("${map.geoCoderUrl}")
    private String geoCoderUrl;

    private JSONObject sendRequest(String url, Map<String, String> param) throws Exception {
        String result = HttpUtils.newRequest()
                .get(url)
                .parameters(param)
                .parameter("key", securityKey)
                .parameter("output", "json").executeForString();
        JSONObject resp = JSON.parseObject(result);
        String status = resp.getString("status");
        if ("347".equals(status)) {
            return null;
        } else if (!"0".equals(status)) {
            throw new Exception(resp.getString("message"));
        }
        return resp.getJSONObject("result");
    }

    public double[] resolveAddress(String address) {
        Map<String, String> param = new HashMap<>();
        param.put("address", address);
        try {
            JSONObject result = sendRequest(geoCoderUrl, param);
            if (result == null) return null;
            JSONObject location = result.getJSONObject("location");
            if (location == null) return null;
            return new double[]{location.getDouble("lng"), location.getDouble("lat")};
        } catch (Exception e) {
            throw new BusinessException("解析地址经纬度失败", e);
        }
    }
}
